import requests
import base64

API_KEY = "qsJRSYzCqDmctTbi0kaB33qu"
SECRET_KEY = "T7k0koE1NuH8KHM9H5dKSmCbX6UU6JIg"

class GetAccess:
    def __init__(self):
        self.api_key = API_KEY
        self.secret_key = SECRET_KEY

    def get_access_token(self):
        """生成百度OCR的access_token"""
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": self.api_key,
            "client_secret": self.secret_key
        }
        try:
            response = requests.post(url, params=params, timeout=10)
            response.raise_for_status()
            return response.json().get("access_token")
        except Exception as e:
            return None

    def recognize_idcard(self, image_url):
        """
        从七牛云图片URL识别身份证信息
        :param image_url: 七牛云图片公开URL
        :return: 识别结果字典（含name/id_card/address）或错误信息
        """
        # 1. 下载七牛云图片（公开URL直接访问，私有URL需七牛签名，参考后续补充）
        try:
            # 忽略七牛测试域名的SSL证书错误（开发环境临时用，生产环境需绑定备案域名）
            requests.packages.urllib3.disable_warnings()
            img_response = requests.get(image_url, timeout=15, verify=False)
            print(img_response)
            img_response.raise_for_status()  # 抛出HTTP错误（如404/500）
        except Exception as e:
            return {"error": f"图片下载失败：{str(e)}","img":{"img_url":image_url}}

        # 2. 图片转为Base64（百度OCR要求的格式）
        try:
            image_base64 = base64.b64encode(img_response.content).decode("utf-8")
        except Exception as e:
            return {"error": f"图片转Base64失败：{str(e)}"}

        # 3. 调用百度身份证OCR接口
        access_token = self.get_access_token()
        if not access_token:
            return {"error": "获取百度OCR令牌失败"}

        ocr_url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={access_token}"
        payload = {
            "image": image_base64,
            "id_card_side": "front",  # 身份证正面
            "detect_ps": False,
            "detect_risk": False
        }
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}

        try:
            ocr_response = requests.post(ocr_url, data=payload, headers=headers, timeout=15)
            ocr_result = ocr_response.json()
        except Exception as e:
            return {"error": f"百度OCR接口调用失败：{str(e)}"}

        # 4. 处理OCR响应结果
        if "error_code" in ocr_result:
            return {"error": f"OCR识别失败：{ocr_result['error_msg']}"}
        if "words_result" not in ocr_result:
            return {"error": "OCR返回格式异常，未识别到身份证信息"}

        # 提取关键信息（百度OCR返回的字段在words_result中）
        words_result = ocr_result["words_result"]
        return {
            "name": words_result.get("姓名", {}).get("words", "").strip(),
            "id_card": words_result.get("公民身份号码", {}).get("words", "").strip(),
            "address": words_result.get("住址", {}).get("words", "").strip()
        }

    def main(self):
        """原测试方法（可保留用于本地调试）"""
        # 本地调试时，替换为七牛云图片URL
        test_image_url = "https://t4xo72tlu.hn-bkt.clouddn.com/idcard/xxx.png"
        result = self.recognize_idcard(test_image_url)
        print(result)

if __name__ == '__main__':
    accessor = GetAccess()
    accessor.main()